package ui.activity.autogenerating_test_paper;

import android.os.Bundle;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.TextView;

import com.chad.library.adapter.base.BaseQuickAdapter;

import org.angmarch.views.NiceSpinner;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import adapter.QuestionTypeAdapter;
import adapter.QuestionTypeNumAdapter;
import base.BaseBean;
import base.activity.BaseNetActivity;
import bean.ChapterBean;
import bean.GradeSubjectsBean;
import bean.LoreBean;
import bean.QuestionTypeBean;
import bean.TextBookBean;
import bean.VersionBean;
import student.andlei.com.student.R;
import utils.GsonUtils;
import utils.SPUtils;
import utils.StringUtils;
import view.FourLayerPopupWindow;

/**
 * 智能组卷
 */
public class IntelligentTestPaperOptionActivity extends BaseNetActivity {
    private Button bt_next;
    private NiceSpinner niceSpinner_subject;
    private GradeSubjectsBean subjectsBean;
    private AdapterView.OnItemSelectedListener onItemSelectedListener = new AdapterView.OnItemSelectedListener() {
        @Override
        public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
            switch (adapterView.getId()) {
                case R.id.spann_select_subject:
                    nowDegree_id = subjectsBeanLists.get(i).degree_id;
                    nowGradeSubject_id = subjectsBeanLists.get(i).subject_id;
                    restoreTvChapter();
                    postTextbookAndLore();
                    GetQuestionType();
                    break;
            }
        }

        @Override
        public void onNothingSelected(AdapterView<?> adapterView) {

        }
    };
    private TextView niceSpinner_zhangejie;
    private List<QuestionTypeBean> questionTypeBeanList = new ArrayList<>();
    private QuestionTypeAdapter typeAdapter;
    private QuestionTypeNumAdapter typenumAdapter;
    private RecyclerView rcly_questiontype;
    private RecyclerView rcly_questiontype_num;
//    private CheckBox check_xuanze,
//            check_tiankong,
//            check_jieda;
    private CheckBox check_buxian,
            check_jichu,
            check_zhongdang,
            check_nanti,
            check_four,
            check_five;
    private EditText ed_xuanze,
            ed_tiankong,
            ed_jieda;
    private CheckBox check_all,
            check_pingtai,
            check_school,
            check_my;
    private int nowDegree_id;
    private int nowGradeSubject_id;
    private List<VersionBean> version_list = new ArrayList<>();
    private List<TextBookBean> textBook_list = new ArrayList<>();
    private List<ChapterBean> Chapter_list = new ArrayList<>();
    private List<LoreBean> lore_list = new ArrayList<>();
    private VersionBean versionBean;
    private TextBookBean textBookBean;
    //private LinearLayout llContainer;
    private String nowTextbook_chapter_id;
//    private ChapterBean saveChapterBean = new ChapterBean();
//    private List<String> gradeSubjectList = new ArrayList<>();
//    private List<GradeSubjectBean.DataBean.ListBean> gradeSubjectBeanList = new ArrayList<>();
    private  List<GradeSubjectsBean.mlist> subjectsBeanLists = new ArrayList<>();
    private FourLayerPopupWindow fourLayerPopupWindow;
    private LoreBean loreBean;
    private String nowLore_id;
//    private List<GetSubjectBean> beanList;
//    private List<String> allsubjectList = new ArrayList<>();
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setTitle("智能组卷");
    }
    @Override
    public void success(String action, BaseBean baseBean) {
        if (baseBean.getCode() != 200) {
            toast(baseBean.msg);
            return;
        }
//        if(action.equals("schedule/getSubject")){
//            beanList = GsonUtils.getInstance(context).parseNoHeaderJArray(baseBean, GetSubjectBean.class);
//            GetSubjectBean bean0 = new GetSubjectBean();
//            bean0.subject_name = "请选择科目";
//            bean0.subject_id = 0;
//            beanList.add(0, bean0);
//            for (GetSubjectBean bean : beanList) {
//                allsubjectList.add(bean.subject_name);
//            }
//            niceSpinner_subject.attachDataSource(allsubjectList);
//        }
        if (action.equals("common/gradeSubjects")) {
            List<GradeSubjectsBean> subjectsBeanList = new ArrayList<>();
            subjectsBeanList =  GsonUtils.getInstance(context).parseNoHeaderJArray(baseBean,GradeSubjectsBean.class);
            for(int i=0;i<subjectsBeanList.size();i++){
                for(int j=0;j<subjectsBeanList.get(i).list.size();j++){
                    subjectsBeanList.get(i).list.get(j).subject_name = subjectsBeanList.get(i).grade_name+subjectsBeanList.get(i).list.get(j).subject_name;
                }
                subjectsBeanLists.addAll(subjectsBeanList.get(i).list);
            }
            setGradeSubjectListData();
        }else if(action.equals("common/textbook")){
            textBook_list = GsonUtils.getInstance(context).parseHaveHeaderJArray(baseBean,TextBookBean.class,"list");
            //textBookBean = (TextBookBean) baseBean;
        }else if(action.equals("common/lore")){
            lore_list = GsonUtils.getInstance(context).parseHaveHeaderJArray(baseBean,LoreBean.class,"list");
            //List<LoreBean> list = data.getList();
        }else if(action.equals("common/version")){
            version_list = GsonUtils.getInstance(context).parseNoHeaderJArray(baseBean,VersionBean.class);
           // versionBean = (VersionBean) baseBean;
        }else if(action.equals("common/chapter")){
            Chapter_list = GsonUtils.getInstance(context).parseNoHeaderJArray(baseBean,ChapterBean.class);
//          ChapterBean chapterBean = (ChapterBean) baseBean;
           fourLayerPopupWindow.notifyChapterData(Chapter_list);
        }else if(action.equals("common/questionType")){
            questionTypeBeanList = GsonUtils.getInstance(context).parseNoHeaderJArray(baseBean,QuestionTypeBean.class);
            typeAdapter.setNewData(questionTypeBeanList);
            typenumAdapter.setNewData(questionTypeBeanList);
        }

    }

    @Override
    public void error(String action, Throwable e) {

    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_autogeneratingtestpaper;
    }

    @Override
    protected void findViews() {
        niceSpinner_subject = getView(R.id.spann_select_subject);
        niceSpinner_zhangejie = getView(R.id.spann_select_chapter);
        rcly_questiontype =getView(R.id.rcly_);
        rcly_questiontype_num = getView(R.id.rcly_two);
        //------------------------------------------------
//        check_xuanze = getView(R.id.check_xuanze);
//        check_tiankong = getView(R.id.check_tiankong);
//        check_jieda = getView(R.id.check_jieda);
        //--------------------------------
        check_buxian = getView(R.id.check_buxian);
        check_jichu = getView(R.id.check_jichu);
        check_zhongdang = getView(R.id.check_zhongdang);
        check_nanti = getView(R.id.check_nanti);
        check_four = getView(R.id.check_jiaonan);
        check_five = getView(R.id.check_kunnan);
        //----------------------------------
//        ed_xuanze = getView(R.id.ed_xuanze);
//        ed_tiankong = getView(R.id.ed_tiankong);
//        ed_jieda = getView(R.id.ed_jieda);
        //---------------------------------
        check_all = getView(R.id.check_all);
        check_pingtai = getView(R.id.check_pingtai);
        check_school = getView(R.id.check_school);
        check_my = getView(R.id.check_my);

        bt_next = getView(R.id.bt_next);
    }

    private void setGradeSubjectListData() {
        List<String> stringList = new ArrayList<>();
        for(int i=0;i<subjectsBeanLists.size();i++){
            stringList.add(subjectsBeanLists.get(i).subject_name);
        }
        niceSpinner_subject.attachDataSource(stringList);
        if (subjectsBeanLists.size() > 0) {
            initSubjectSpinner();
        }
    }

    private void initSubjectSpinner() {
        niceSpinner_subject.setSelectedIndex(0);
        nowDegree_id = subjectsBeanLists.get(0).degree_id;
        nowGradeSubject_id = subjectsBeanLists.get(0).subject_id;
        postTextbookAndLore();
        GetQuestionType();
    }

    private void postTextbookAndLore() {
        Map<String, String> textbookMap = new HashMap<>();
        textbookMap.put("subject_id", "" + nowGradeSubject_id);
        textbookMap.put("degree_id", "" + nowDegree_id);
        textbookMap.put("version_id", "0");//0代表所有
        post("common/textbook", textbookMap, TextBookBean.class, false);

        Map<String, String> map = new HashMap<>();
        map.put("subject_id", nowGradeSubject_id + "");
        map.put("grade_id", nowDegree_id + "");
        post("common/lore", map, LoreBean.class, false);
    }
    //获取题目类型
    private void GetQuestionType(){
        Map<String, String> map = new HashMap<>();
        map.put("subject_id", nowGradeSubject_id + "");
        post("common/questionType", map, LoreBean.class, false);
    }
    @Override
    protected void formatViews() {
        GridLayoutManager layoutManager = new GridLayoutManager(context,7);
        rcly_questiontype.setLayoutManager(layoutManager);
        typeAdapter = new QuestionTypeAdapter(R.layout.item_questiontype,questionTypeBeanList);
        rcly_questiontype.setAdapter(typeAdapter);
        GridLayoutManager slayoutManager = new GridLayoutManager(context,5);
        rcly_questiontype_num.setLayoutManager(slayoutManager);
        typenumAdapter = new QuestionTypeNumAdapter(R.layout.item_questiontype_num,questionTypeBeanList);
        rcly_questiontype_num.setAdapter(typenumAdapter);
        typeAdapter.setOnItemChildClickListener(new BaseQuickAdapter.OnItemChildClickListener() {
            @Override
            public void onItemChildClick(BaseQuickAdapter adapter, View view, int position) {
                    if(view.getId()==R.id.check_xuanze){
                        questionTypeBeanList.get(position).isSelect = !questionTypeBeanList.get(position).isSelect;
                        adapter.notifyDataSetChanged();
                    }
            }
        });
        //--------------------------------------------
        niceSpinner_subject.setOnItemSelectedListener(onItemSelectedListener);
        bt_next.setOnClickListener(this);
        niceSpinner_zhangejie.setOnClickListener(this);
        check_buxian.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (isChecked) {
                    update_checkdifficulty();
                    check_buxian.setChecked(true);
                }
            }
        });
        check_jichu.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (isChecked) {
                    update_checkdifficulty();
                    check_jichu.setChecked(true);
                }
            }
        });
        check_zhongdang.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (isChecked) {
                    update_checkdifficulty();
                    check_zhongdang.setChecked(true);
                }
            }
        });
        check_nanti.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (isChecked) {
                    update_checkdifficulty();
                    check_nanti.setChecked(true);
                }
            }
        });

    }

    @Override
    protected void formatData() {
        postSubjectAndVersion();
    }


    @Override
    protected void getBundle(Bundle bundle) {

    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.bt_next:

                Bundle bundle = new Bundle();
               // jumpTo(AutogeneratingTestPaperListActivity.class, bundle);
                bundle.putInt("degree_id",nowDegree_id);
                bundle.putInt("subject_id", nowGradeSubject_id);
                bundle.putString("textbook_chapter_id", nowTextbook_chapter_id);
                bundle.putString("lore_id",nowLore_id);
                if (nowGradeSubject_id == 0 ) {
                    toast("请选择科目");
                    return;
                }
                if(TextUtils.isEmpty(nowTextbook_chapter_id)&& StringUtils.isNull(nowLore_id)){
                    toast("请选择章节或知识点");
                    return;
                }
                //难度 1容易, 2较易, 3一般, 4较难, 5困难
                String difficult = "";
                if (check_buxian.isChecked()) {
                    difficult = "0";
                } else if (check_jichu.isChecked()) {
                    difficult = "1";
                } else if (check_zhongdang.isChecked()) {
                    difficult = "2";
                } else if (check_nanti.isChecked()) {
                    difficult = "3";
                }else if (check_four.isChecked()) {
                    difficult = "4";
                }else if (check_five.isChecked()) {
                    difficult = "5";
                }
                if (TextUtils.isEmpty(difficult)) {
                    toast("请选择题目难度");
                    return;
                }
                bundle.putString("difficulty", difficult);


                //来源 0引用 1平台 2学校 3老师
                String str = "";
                if (check_all.isChecked()) {
                    str = str + "0";
                }
                if (check_pingtai.isChecked()) {
                    str = str + ",1";
                }
                if (check_school.isChecked()) {
                    str = str + ",2";
                }
                if (check_my.isChecked()) {
                    str = str + ",3";
                }
                bundle.putString("source_type", str);
                if (TextUtils.isEmpty(str)) {
                    toast("请选择题目来源");
                    return;
                }

                //题目类型
                Map<String, String> map = new HashMap();
                for(QuestionTypeBean questionTypeBean: questionTypeBeanList){
//                    if(questionTypeBean.isSelect){
                        if(questionTypeBean.inputNum>0){
                            map.put(""+questionTypeBean.type_id,questionTypeBean.inputNum+"");
                        }
//                            toast("请输入题目数量");
//                            return;
//                        }else {
//
//                        }
//                    }
                }
                if(map.size()<=0){
                    toast("请输入题目类型");
                    return;
                }
                String questions = SPUtils.toJson(true, map);
                bundle.putString("questions", "" + questions);
                jumpTo(AutogeneratingTestPaperListActivity.class, bundle);
                finish();
                break;
            case R.id.spann_select_chapter:
                if (nowGradeSubject_id == 0) {
                    toast("请选择科目");
                }
                if (version_list.size() <=0  || textBook_list.size() <= 0 || lore_list.size() <= 0) {
                    return;
                }
                fourLayerPopupWindow = new FourLayerPopupWindow(IntelligentTestPaperOptionActivity.this, version_list, textBook_list, lore_list);
                fourLayerPopupWindow.setOnSelectChapterAndLoreIdListener(new FourLayerPopupWindow.OnSelectChapterAndLoreIdListener() {
                    @Override
                    public void onSelectTextBookId(int textBookId) {
                        Map<String, String> map = new HashMap<>();
                        map.put("textbook_id", textBookId + "");
                        post("common/chapter", map, ChapterBean.class, false);
                    }

                    @Override
                    public void onSelectChapterId(List<ChapterBean> saveChapterDataBeanList) {
                        if (saveChapterDataBeanList.size() > 0) {
                            String temp_chapterId = "";
                            String temp_chapterName = "";
                            for (ChapterBean saveDataBean : saveChapterDataBeanList) {
                                if(saveDataBean.isSelectId){
                                    temp_chapterId = temp_chapterId + saveDataBean.getChapter_id() + ",";
                                    temp_chapterName = temp_chapterName + saveDataBean.getChapter_title() + "，";//中文逗号
                                }
                            }
                            if(StringUtils.isNull(temp_chapterId)){toast("请选择章节"); return;}
                            nowTextbook_chapter_id = temp_chapterId.substring(0, temp_chapterId.length() - 1);
                            nowLore_id = null;
                            niceSpinner_zhangejie.setText(temp_chapterName.substring(0, temp_chapterName.length() - 1));
                        } else {
                            restoreTvChapter();
                        }

                    }


                    @Override
                    public void onSelectLoreId(List<LoreBean> saveLoreListBeanList) {
                        if (saveLoreListBeanList.size() > 0) {
                            String temp_loreId = "";
                            String temp_loreContent = "";
                            for (LoreBean saveDataBean : saveLoreListBeanList) {
                                if(saveDataBean.isSelectId){
                                    temp_loreId = temp_loreId + saveDataBean.lore_id + ",";
                                    temp_loreContent = temp_loreContent + saveDataBean.lore_content + "，";//中文逗号
                                }
                            }
                            if(StringUtils.isNull(temp_loreId)){
                                toast("请选择知识点");
                                return;
                            }
                            nowLore_id = temp_loreId.substring(0, temp_loreId.length() - 1);
                            nowTextbook_chapter_id = null;
                            niceSpinner_zhangejie.setText(temp_loreContent.substring(0, temp_loreContent.length() - 1));
                        } else {
                            restoreTvChapter();
                        }


                    }


                });
                fourLayerPopupWindow.showAsDropDown(niceSpinner_zhangejie);
                break;
        }
    }

    private void update_checkdifficulty() {
        check_buxian.setChecked(false);
        check_jichu.setChecked(false);
        check_zhongdang.setChecked(false);
        check_nanti.setChecked(false);
    }

    private void update_checksource() {
        check_all.setChecked(false);
        check_pingtai.setChecked(false);
        check_school.setChecked(false);
        check_my.setChecked(false);
    }

    private void restoreTvChapter() {
        niceSpinner_zhangejie.setText("选择章节或知识点");
        nowTextbook_chapter_id = null;
        nowLore_id = null;
    }

    private void postSubjectAndVersion() {
//      Map<String, String> map = new HashMap<>();
        post("common/gradeSubjects",  GradeSubjectsBean.class, false);
 //       post("/common/gradeSubjects", GradeSubjectBean.class, false);


        post("common/version", VersionBean.class, false);
    }
}
